package com.malou.client.ventas.tienda;

import java.util.ArrayList;
import java.util.List;

import com.extjs.gxt.ui.client.util.IconHelper;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.Dialog;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.grid.CheckBoxSelectionModel;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.grid.filters.GridFilters;
import com.extjs.gxt.ui.client.widget.grid.filters.NumericFilter;
import com.extjs.gxt.ui.client.widget.grid.filters.StringFilter;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.toolbar.PagingToolBar;
import com.extjs.gxt.ui.client.widget.toolbar.SeparatorToolItem;
import com.extjs.gxt.ui.client.widget.toolbar.ToolBar;
import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.NumberFormat;
import com.malou.client.MalouConstants;
import com.malou.client.MalouMessages;
import com.malou.client.util.Utilities;
import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.data.BeanModel;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.GridEvent;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.MessageBoxEvent;
import com.extjs.gxt.ui.client.event.SelectionChangedEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;

public class TiendaPanel extends ContentPanel {
		
	TiendaDialog dialog;
	private BeanModel selectedModel;
	private Button addTienda;
	private Button editTienda;
	private Button deleteTienda;
	private MalouConstants constants = GWT.create(MalouConstants.class);
	private MalouMessages messages = GWT.create(MalouMessages.class);
	private List<BeanModel> selectedModels;
	private Integer selectedSize;
	private ToolBar toolBar;
	private SeparatorToolItem separatorAdd;
	private SeparatorToolItem separatorEdit;	
	
	public TiendaPanel(){
		
		Tiendas.getPaginate();
		
        final PagingToolBar toolBarPag = new PagingToolBar(Utilities.itemsPerPage);
        toolBarPag.bind(Tiendas.loader);
        
        List<ColumnConfig> columns = new ArrayList<ColumnConfig>();
        
        final CheckBoxSelectionModel<BeanModel> sm = new CheckBoxSelectionModel<BeanModel>();
        
        columns.add(sm.getColumn());
        columns.add(new ColumnConfig("nombre", constants.tiendaNombre(), 150));
        
        ColumnConfig column = new ColumnConfig("costoalquiler", constants.tiendaCostoAlquiler(), 150);
        column.setAlignment(HorizontalAlignment.RIGHT);
        column.setNumberFormat(NumberFormat.getFormat("0.00"));
        columns.add(column);
        columns.add(new ColumnConfig("ubicacion", constants.tiendaUbicacion(), 150));
        columns.add(new ColumnConfig("telefono", constants.tiendaTelefono(), 150));
      
        ColumnModel cm = new ColumnModel(columns);
        
        Grid<BeanModel> grid = new Grid<BeanModel>(Tiendas.store, cm);  
        grid.addListener(Events.Attach, new Listener<GridEvent<BeanModel>>() {  
          public void handleEvent(GridEvent<BeanModel> be) {  
        	  Tiendas.loader.load(0, Utilities.itemsPerPage);  
          }  
        });   
        
        grid.setLoadMask(true);  
        grid.setBorders(true);               
                
        this.setFrame(true);  
        this.setCollapsible(true);  
        this.setAnimCollapse(false);  
        
        this.setIcon(IconHelper.createPath("images/icons/table.png"));  
        this.setHeading(constants.tiendaListaTiendas());  
        this.setLayout(new FitLayout());
        
        toolBar = new ToolBar(); 
        addTienda = new Button(constants.agregar(), IconHelper.createPath("images/icons/new.gif"));
        
        //inserta  los Store en los Dialog que estan dentro del FormPanel
        dialog = new TiendaDialog();		
		dialog.setStore(Tiendas.store);
		
        SelectionListener<ButtonEvent> sl_add;        
        sl_add = new SelectionListener<ButtonEvent>(){

			@Override
			public void componentSelected(ButtonEvent ce) {				
				dialog.reset();
				dialog.unbind();
			    dialog.show();
			}
			
		};
		addTienda.addSelectionListener(sl_add);
        toolBar.add(addTienda);
        separatorAdd = new SeparatorToolItem();
        toolBar.add(separatorAdd);
        deleteTienda = new Button(constants.eliminar(), IconHelper.createPath("images/icons/delete.gif"));
        deleteTienda.setEnabled(false);
        final Listener<MessageBoxEvent> l = new Listener<MessageBoxEvent>() {  
          public void handleEvent(MessageBoxEvent ce) {  
            String button_id = ce.getButtonClicked().getItemId();  
             if(Dialog.YES == button_id){
            	 Tiendas.tiendaDialog = dialog;
        		 
            	 if(selectedSize == 1){
            		 Integer id = selectedModel.get("id");            		 
            		 Tiendas.delete(id);
            	 }else if(selectedSize > 1){
            		 String ids = Utilities.toIds(selectedModels);            		 
            		 Tiendas.deleteAll(ids);
            	 }
             }
          }  
        };
        
        SelectionListener<ButtonEvent> sl_delete;
        sl_delete = new SelectionListener<ButtonEvent>(){

			@Override
			public void componentSelected(ButtonEvent ce) {
				String mensaje="";
				if(selectedSize == 1){
					String tienda = selectedModel.get("nombre");
					
					mensaje = messages.tiendaEstaSeguro(tienda);					
				}else if(selectedSize > 1){
					mensaje = constants.eliminarAll();
				}
				MessageBox.confirm(constants.confirmacion(), mensaje, l).getDialog().getButtonById(Dialog.YES).setText(constants.si());
				
			}
			
		};
		deleteTienda.addSelectionListener(sl_delete);
        toolBar.add(deleteTienda);
        separatorEdit = new SeparatorToolItem(); 
        toolBar.add(separatorEdit);  
        
        editTienda = new Button(constants.editar(), IconHelper.createPath("images/icons/update.png"));
        editTienda.setEnabled(false);
        toolBar.add(editTienda);
        
        SelectionListener<ButtonEvent> sl_edit;        
        sl_edit = new SelectionListener<ButtonEvent>(){

			@Override
			public void componentSelected(ButtonEvent ce) {	
				dialog.bind(selectedModel);
				dialog.beforeEdit();
			    dialog.show();
			}
			
		};
		editTienda.addSelectionListener(sl_edit);
        this.setTopComponent(toolBar); 
                
        grid.setSelectionModel(sm);
        grid.getSelectionModel().addListener(Events.SelectionChange,
                new Listener<SelectionChangedEvent<BeanModel>>() {

				@Override
				public void handleEvent(SelectionChangedEvent<BeanModel> be) {		
					selectedSize = be.getSelection().size();
					if(selectedSize==0){
						editTienda.setEnabled(false);
		            	dialog.unbind();
		            	deleteTienda.setEnabled(false);
					}else if(selectedSize==1){
						selectedModel = be.getSelectedItem();
						dialog.bind(selectedModel);
		            	editTienda.setEnabled(true);
		            	deleteTienda.setEnabled(true);
					}else if(selectedSize > 1){
						selectedModels = be.getSelection();						
						editTienda.setEnabled(false);						
						dialog.unbind();
						deleteTienda.setEnabled(true);
					}					
				}
        	
        });
        
        GridFilters filters = new GridFilters();
        filters.getMessages().setFilterText(constants.filtros());
        
        StringFilter nombreFilter = new StringFilter("nombre");        
        
        StringFilter ubicacionFilter = new StringFilter("ubicacion");
        StringFilter telefonoFilter = new StringFilter("telefono");
        NumericFilter costoalquiler = new NumericFilter("costoalquiler");
        
        filters.addFilter(nombreFilter);        
        filters.addFilter(ubicacionFilter);
        filters.addFilter(telefonoFilter);
        filters.addFilter(costoalquiler);
        
        grid.addPlugin(filters);                
        
        this.setBottomComponent(toolBarPag);
                
        grid.addPlugin(sm);
        
        this.add(grid);
		this.setHeaderVisible(true);		
		
	}
	
	public void setPermisos(List<String> permisos){
		
		boolean add = permisos.contains("add");
		boolean edit = permisos.contains("edit");
		boolean delete = permisos.contains("delete");
		
		if(!add && !edit && !delete){
			toolBar.setVisible(false);
		}else{
			if(!add){
				addTienda.setVisible(false);
				separatorAdd.setVisible(false);
			}
			if(!edit){
				editTienda.setVisible(false);
				separatorEdit.setVisible(false);
			}
			if(!delete)
				deleteTienda.setVisible(false);
		}
	}
}
